
#include "Player.h"
#include "Entity.h"
#include "Engine.h"
#include "Camera.h"
#include "Input.h"
#include "TerrainGeom.h"

//
// Constructor
//

Player::Player(const string &_name)
{
	name = _name;
}

//
// KeyResponse
//

void Player::KeyResponse()
{
	Real3 forward = engine.camera->Direction();
	forward.y = 0;
	forward.Normalize();
	forward *= engine.camera->linearSpeed;
	
	Real3 right = engine.camera->Right();
	right.y = 0;
	right.Normalize();
	right *= engine.camera->linearSpeed;

	if(input.KeyPressed(DIK_W))
		TryMove( forward);
	if(input.KeyPressed(DIK_S))
		TryMove(-1.0f * forward);

	if(input.KeyPressed(DIK_D))
		TryMove( right);
	if(input.KeyPressed(DIK_A))
		TryMove(-1.0f * right);
		
	if(input.MouseZ())
	{
	  engine.camera->IncreaseZoom(input.MouseZ() * 0.002f);
	}

	if(input.KeyPressed(DIK_SPACE) && fEquals(model->GetLinearVelocity().y, 0.0f, 0.10f))
		model->AccelerateLinearVelocity(Vector3(0.0, 6.0, 0.0));
	
	if(input.MouseX())
		model->Rotate(Real3(0.0f, engine.camera->rotationalSpeed * engine.camera->xSensitivity * input.MouseX() * 0.07f, 0.0f));

	/*if(engine.terrain)
	{
		Real3 p = model->Position();
		p.y = engine.terrain->GetHeight(p) + 1.0f;
		model->SetPosition(p);
	}*/

	// Updates camera position
	#ifdef FIRST_PERSON
	engine.camera->SetPosition(model->Position() + Real3(0.0f, 1.0f, 0.0f));
	#else
	engine.camera->SetPosition(model->Position() + engine.camera->Up() - 2*engine.camera->Direction());
	#endif
}

//
// Try Move
//

void Player::TryMove(Vector3 move)
{
	Real3 oldPos = model->Position();

	model->Translate(move * engine.lastFrameLength);

	if(model->HasOctree() && engine.CollisionTest(model))
		model->SetPosition(oldPos);
}
